﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;
using System.Runtime.InteropServices;
using System.Net;
using System.Threading;
using System.Diagnostics;

namespace 自动更新客户端
{
    public partial class updateclient : Form
    {
        XmlDocument update=new XmlDocument();
        XmlReader updatereader;
        XmlDocument clientinfo = new XmlDocument();
        XmlReader clientreader;
        string _UpdateName;
        string _UpdateVersion;
        string _UpdateVersionDate;
        string _UpdateUrl;
        string _UpdateDescribe;
        string _CurrentName;
        string _CurrentVersion;
        string _CurrentVersionDate = "20120101";
        string _XML = "http://sentence.sinaapp.com/update.xml";
        WebClient downclient = new WebClient();

        //判断网络连接
        [DllImport("wininet")]
        private extern static bool InternetGetConnectedState(out int connectionDescription, int reservedValue);
        ///<summary>
        /// 检测本机的网络连接
        ///</summary>

        public updateclient()
        {
            MessageBox.Show("updater.exe由主程序自动调用， 请勿手动打开~！");
            InitializeComponent();
            this.Close();
            Application.Exit();
        }
        public updateclient(string[] args)
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
            //             Thread Thread_checkVersion = new Thread(new ThreadStart(checkVersion));
            //             Thread_checkVersion.IsBackground = true;
            //             Thread_checkVersion.Start();
            checkVersion();
        }

        private void checkVersion()
        {
            try
            {
                string s = "";
                clientinfo.Load(Application.StartupPath + @"\app.xml");
                clientreader = new XmlNodeReader(clientinfo);
                while (clientreader.Read())
                {
                    switch (clientreader.NodeType)
                    {
                        case XmlNodeType.Element:
                            s = clientreader.Name;
                            break;
                        case XmlNodeType.Text:
                            if (s.Equals("Name"))
                                _CurrentName = clientreader.Value.ToString();
                            if (s.Equals("Version"))
                                _CurrentVersion = clientreader.Value.ToString();
                            if (s.Equals("VersionDate"))
                                _CurrentVersionDate = clientreader.Value.ToString();
                            if (s.Equals("XML"))
                                _XML = clientreader.Value.ToString();
                            break;
                    }
                }
                s = "";
                update.Load(_XML);
                updatereader = new XmlNodeReader(update);
                while (updatereader.Read())
                {
                    switch (updatereader.NodeType)
                    {
                        case XmlNodeType.Element:
                            s = updatereader.Name;
                            break;
                        case XmlNodeType.Text:
                            if (s.Equals("Name"))
                                _UpdateName = updatereader.Value.ToString();
                            if (s.Equals("Version"))
                                _UpdateVersion = updatereader.Value.ToString();
                            if (s.Equals("VersionDate"))
                                _UpdateVersionDate = updatereader.Value.ToString();
                            if (s.Equals("Url"))
                                _UpdateUrl = updatereader.Value.ToString();
                            if (s.Equals("Describe"))
                                _UpdateDescribe = updatereader.Value.ToString();
                            break;
                    }

                }


                if (int.Parse(_CurrentVersionDate) < int.Parse(_UpdateVersionDate))
                {
                    MessageBox.Show("当前版本：" + _CurrentVersion + "\n" + "新版本：" +
                        _UpdateVersion + "\n更新内容：\n" +
                        _UpdateDescribe, "发现新版本，点击确定更新",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Information);


                    System.Diagnostics.Process[] pcs = System.Diagnostics.Process.GetProcesses();
                    foreach (System.Diagnostics.Process p in pcs)
                    {
                        if (p.ProcessName == _CurrentName)
                        {
                            p.Kill();
                            p.Dispose();
                            p.Close();
                            Thread.Sleep(1000);
                        }
                            
                    }

                    progressBar1.Visible = true;
                    Thread downfile = new Thread(downloadUpdate);
                    downfile.IsBackground = true;
                    downfile.Start();
                }
                else
                {
                    Application.Exit();
                }
            }
            catch(Exception e)
            {
                MessageBox.Show("更新中发生错误:" + e.ToString(), "啊哦发生了一个错误，请联系作者", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                Application.Exit();
            }

        }

        private void downloadUpdate()
        {
            try
            {
                label1.Text = "下载更新包...";
                downclient.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(downclient_DownloadProgressChanged);
                downclient.DownloadFileCompleted += new AsyncCompletedEventHandler(downclient_DownloadFileCompleted);
                downclient.DownloadFileAsync(new Uri(_UpdateUrl), Application.StartupPath + @"\updatePackage.exe");
            }
            catch(Exception ex)
            {
                //error catch
                MessageBox.Show(ex.ToString(), "发生了一个错误,请联系开发者");
            }
        }
        
        void downclient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            downclient.Dispose();
            Process.Start(Application.StartupPath + @"\updatePackage.exe");
            Application.Exit();
        }

        void downclient_DownloadProgressChanged(object sender, System.Net.DownloadProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
            label2.Text = e.BytesReceived.ToString()+"/"+e.TotalBytesToReceive.ToString();
        }

    }
}
